import { defineStore } from 'pinia';

export const useCustomerStore = defineStore('customer', {
    // 状态
    state: () => {
        return {
            customers: [], // 假设这是一个包含客服列表的状态
            customerNames: {} // 假设这是一个包含客服名字的字典
        };
    },
    // 计算属性
    getters: {
        getLastCustomer: (state) => state.customers[state.customers.length - 1] || null,
        getCustomerById: (state) => (id) => state.customers.find(customer => customer.id === id),
        getCustomerNameById: (state) => (id) => state.customerNames[id] || null // 查找客服名字
    },
    // 方法
    actions: {
        addCustomer(id, name) {
            // 添加客服ID和名字
            if (!this.customerNames[id]) {
                this.customerNames[id] = name;
                this.customers.push({ id, name });
            }
        },
        removeCustomerById(id) {
            // 根据 ID 删除客服信息
            this.customers = this.customers.filter(customer => customer.id !== id);
            delete this.customerNames[id]; // 删除客服名字
        },
        removeCustomerByName(name) {
            // 根据 Name 删除客服信息
            const idToRemove = Object.keys(this.customerNames).find(key => this.customerNames[key] === name);
            if (idToRemove) {
                this.customers = this.customers.filter(customer => customer.name !== name);
                delete this.customerNames[idToRemove]; // 删除客服名字
            }
        },
        updateCustomerNameById(id, newName) {
            // 更新客服名字
            const customer = this.getCustomerById(id);
            if (customer) {
                customer.name = newName;
                this.customerNames[id] = newName;
            }
        },
        findCustomerById(id) {
            return this.getCustomerById(id);
        },
        findCustomerNameById(id) {
            return this.getCustomerNameById(id);
        },
        removeLastCustomer() {
            // 删除最后加入的客服
            if (this.customers.length > 0) {
                const lastCustomer = this.getLastCustomer;
                this.removeCustomerById(lastCustomer.id);
            }
        }
    }
});
